import path from 'path';
import fs from 'fs';
import { fileURLToPath } from "node:url";
import FetchStream from './FetchStream.js';
import axiox from 'axios';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const API = 'http://chatgpt4.maodouketang.com/api/chat-process';

const INIT_PROMPT = fs.readFileSync(path.join(__dirname, 'chatgpt4_prompt.md'), 'utf-8');

/**
 *      tool: 'c2rust',
 *      code: '',
 *      prompt: '',
 *      id: '', // 用于标识不同的的对话
*/

export async function chatgpt4(config) {
    console.log('[chatgpt4] start transcode...');

    console.log('[chatgpt4]', config);
    return new Promise(async (resolve, reject) => {

        // resolve('// chatgpt4 接口未实现');
        // return;

        const data = {
            options: { parentMessageld: config.id },
            prompt: `将以下C代码转译成Rust代码：[${config.code}]`,
            systemMessage: INIT_PROMPT,
            temperature:0.8,
            top_p: 1
        }

        let content = '';
        axiox({
            method: 'POST',
            url: API,
            data,
            responseType: 'stream'
        })
        .then(res => {
            res.data.on('data', (chunk) => {
                // console.log('--------------------------------');
                console.log(chunk.toString('utf-8'));
                content += chunk.toString('utf-8');
            })
            res.data.on('end', () => {
                console.log("传输完成");
                // console.log(content);
                const d = content.split('\n');
                console.log(d);
                const last = JSON.parse(d.pop() || "{}");

                console.log(last.text);

                const reg = /```rust\n([\s\S]*?)```/g;

                let result = '';
                const codes = [];
                while (result = reg.exec(last.text)) {
                    codes.push(result[1]);
                }

                resolve((codes[0] || '').trim());
            });
        })

        // let content = ''; // 拼接每一个分块数据
        // const fetchStream = new FetchStream({
        //     url: API,
        //     requestInit: { // fetch 配置项
        //         method: "POST",
        //         headers: {
        //             "Content-Type": "application/json",
        //             "Accept": "text/event-stream",
        //         },
        //         body: JSON.stringify(data),
        //     },
        //     onmessage: (dataList, _index) => {
        //         // console.log(dataList);
        //         for (const item of dataList) {
        //             console.log('--------------------------------------');
        //             console.log(item);
        //             console.log('--------------------------------------');
        //             try {
        //                 const data_json = JSON.parse(item);
        //                 content += data_json.choices[0].delta.content;
        //                 console.log(content);

        //             } catch (_) {
        //                 // 将解析错误的内容返回缓存，在下一次消息中添加到新消息的头部
        //                 return item;
        //             }
        //         }
        //     },
        //     ondone: () => {
        //         console.log('done!', content);

        //         res.end();
        //     },
        //     ontimeout: () => {
        //         console.log('timeout!');
        //     }
        // });


        // resolve('// chatgpt4 接口未实现');
        return;

        // console.log(answer.choices[0].message.content);

        // const reg = /```rust\n([\s\S]*?)```/g;

        // let result = '';
        // const codes = [];
        // while (result = reg.exec(answer.choices[0].message.content)) {
        //     codes.push(result[1]);
        // }
        // const rust_code = answer.choices[0].message.content.match(/```rust\n([\s\S]*)```/)[1];

        // return codes.join('\n');
        // resolve((codes[0] || '').trim());
    })
}